$(document).ready
(
	function()
	{
		$('#add_keyword_button').click(function(){
			add_keyword();
		});

		$('#filter_comments').click(function(){
			filter_comments();
		});

		$('.enable_keyword').live('click', function(){
			unenable_keyword($(this));
		});

		$('.unenable_keyword').live('click', function(){
			enable_keyword($(this));
		});
	}
)

function add_keyword() {
	var keywords = $('#add_keyword_input').val();

	Common.Api.callJson
	(
		null,
		'Keyword',
		'addKeywords',
		{
			keywords:keywords
		},
		function(result)
		{
			var html = '';
			
			$.each(result, function(key, val){
				html += '<li><a class="enable_keyword" id="' + 
						key + 
						'" name="keyword[]" href="#" style="border:1px #878787 solid; padding:2px; margin:1px;">' + 
	                    val + 
                    	'</a></li>';
			});

			$('#add_keyword_input').val('');
			$('#enable_keywords').append(html);
		}
	)
}


function enable_keyword(keywordDom) {
	
	var idAndReference = keywordDom.attr('id');
	
	Common.Api.callJson
	(
		null,
		'Keyword',
		'enableKeyword',
		{
			idAndReference: idAndReference
		},
		function(result)
		{
			var keyword = $('#'+result.idAndReference).parent('li');
			keyword.remove();
			keyword.find('a').attr('class', 'enable_keyword');
			$('#enable_keywords').append(keyword);
		}
	)
}


function filter_comments() {

	var rawKeywords = [];
	var socialNetwork = $('#filter_social_network').val();

	$('#enable_keywords li').each(function(){
		rawKeywords.push($(this).find('a').html());
	});
console.log(rawKeywords);
	Common.Api.callJson
	(
		null,
		'Keyword',
		'filterComments',
		{
			socialNetwork: socialNetwork,
			rawKeywords: rawKeywords
		},
		function(result)
		{
			$('#filter_result_tbody').html('');
			console.log(result);
			var html =	'';
			$.each(result, function(key, val){
				console.log(val);
				html += '<tr><td class="" id="filter_result_message">' + 
						val.message.content + 
						'</td>' + 
						'<td class="" id="filter_result_comment">' + 
						val.comment.content + 
						'</td>' +
						'<td class="" id="filter_result_userid">' + 
						val.comment.accountId + 
						'</td>' +
						'</tr>';
			});

			
			$('#filter_result_tbody').append(html);
			$('#filter_result').show();
		}
	);
}


function unenable_keyword(keywordDom) {
	
	var idAndReference = keywordDom.attr('id');
	
	Common.Api.callJson
	(
		null,
		'Keyword',
		'unenableKeyword',
		{
			idAndReference: idAndReference
		},
		function(result)
		{
			var keyword = $('#'+result.idAndReference).parent('li');
			keyword.remove();
			keyword.find('a').attr('class', 'unenable_keyword');
			$('#unenable_keywords').append(keyword);
		}
	)
}